from django.test import TestCase
from django.contrib.auth.models import User
from django.utils import timezone
from rest_framework.test import APIClient
from rest_framework import status
from datetime import datetime, timedelta
from .models import StudyRecord, StudyGoal, StudyStatistics

class StudyTests(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.user = User.objects.create_user(
            username='testuser',
            password='testpass123'
        )
        self.client.force_authenticate(user=self.user)
        
        # 创建测试数据
        self.study_record_data = {
            'stage': 'study',
            'duration': 30,
            'start_time': timezone.now(),
            'end_time': timezone.now() + timedelta(minutes=30),
            'notes': '测试学习记录'
        }
        
        self.study_goal_data = {
            'period': 'daily',
            'target_time': 120,
            'start_date': timezone.now().date(),
            'end_date': timezone.now().date() + timedelta(days=7)
        }

    def test_create_study_record(self):
        response = self.client.post(
            '/api/study/records/',
            self.study_record_data,
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(StudyRecord.objects.count(), 1)
        self.assertEqual(StudyRecord.objects.get().user, self.user)

    def test_create_study_goal(self):
        response = self.client.post(
            '/api/study/goals/',
            self.study_goal_data,
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(StudyGoal.objects.count(), 1)
        self.assertEqual(StudyGoal.objects.get().user, self.user)

    def test_get_study_statistics(self):
        # 创建一些学习记录
        StudyRecord.objects.create(
            user=self.user,
            **self.study_record_data
        )
        
        response = self.client.get('/api/study/statistics/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('total', response.data)
        self.assertIn('daily', response.data)
